package com.warom.sdg.websocket;

import android.util.Log;

import com.warom.sdg.util.LogUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

/**
 * WebSocket客户端工具类
 * 提供WebSocket连接、消息发送、断线重连等功能
 */
public class WebSocketClient {
    private static final String TAG = "WebSocketClient";
    
    // WebSocket连接状态
    public enum ConnectionState {
        CONNECTING,
        CONNECTED,
        DISCONNECTED,
        RECONNECTING,
        FAILED
    }
    
    // WebSocket实例
    private WebSocket webSocket;
    private String wsUrl;
    private OkHttpClient client;
    private WebSocketListener listener;
    private ConnectionState state = ConnectionState.DISCONNECTED;
    
    // 消息监听器
    private WebSocketMessageListener messageListener;
    
    /**
     * WebSocket消息监听接口
     */
    public interface WebSocketMessageListener {
        void onConnected();
        void onDisconnected();
        void onMessage(String text);
        void onMessage(ByteString bytes);
        void onError(String error);
    }
    
    /**
     * 构造函数
     * @param wsUrl WebSocket服务器URL
     */
    public WebSocketClient(String wsUrl) {
        this.wsUrl = wsUrl;
        
        // 创建OkHttpClient
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .pingInterval(30, TimeUnit.SECONDS)
                .build();
        
        // 初始化WebSocketListener
        this.listener = createWebSocketListener();
    }
    
    /**
     * 设置消息监听器
     */
    public void setMessageListener(WebSocketMessageListener listener) {
        this.messageListener = listener;
    }
    
    /**
     * 连接到WebSocket服务器
     */
    public void connect() {
        if (state == ConnectionState.CONNECTED || state == ConnectionState.CONNECTING) {
            return;
        }
        
        try {
            state = ConnectionState.CONNECTING;
            Log.d(TAG, "开始连接WebSocket: " + wsUrl);
            
            // 创建请求
            Request request = new Request.Builder()
                    .url(wsUrl)
                    .build();
            
            // 创建WebSocket连接
            webSocket = client.newWebSocket(request, listener);
            
        } catch (Exception e) {
            state = ConnectionState.FAILED;
            Log.e(TAG, "连接WebSocket失败: " + e.getMessage(), e);
            
            if (messageListener != null) {
                messageListener.onError("连接失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 断开WebSocket连接
     */
    public void disconnect() {
        if (webSocket != null) {
            try {
                state = ConnectionState.DISCONNECTED;
                Log.d(TAG, "断开WebSocket连接");
                webSocket.close(1000, "正常关闭");
                webSocket = null;
            } catch (Exception e) {
                Log.e(TAG, "断开连接异常: " + e.getMessage(), e);
            }
        }
    }
    
    /**
     * 发送文本消息
     * @param message 要发送的消息
     * @return 是否发送成功
     */
    public boolean sendMessage(String message) {
        if (webSocket != null && state == ConnectionState.CONNECTED) {
            try {
                return webSocket.send(message);
            } catch (Exception e) {
                Log.e(TAG, "发送消息异常: " + e.getMessage(), e);
                return false;
            }
        } else {
            Log.e(TAG, "发送失败: WebSocket未连接");
            return false;
        }
    }
    
    /**
     * 发送二进制消息
     * @param bytes 要发送的二进制数据
     * @return 是否发送成功
     */
    public boolean sendMessage(ByteString bytes) {
        if (webSocket != null && state == ConnectionState.CONNECTED) {
            try {
                return webSocket.send(bytes);
            } catch (Exception e) {
                Log.e(TAG, "发送二进制消息异常: " + e.getMessage(), e);
                return false;
            }
        } else {
            Log.e(TAG, "发送失败: WebSocket未连接");
            return false;
        }
    }
    
    /**
     * 获取当前连接状态
     * @return 连接状态
     */
    public ConnectionState getState() {
        return state;
    }
    
    /**
     * 创建WebSocketListener
     * @return WebSocketListener实例
     */
    private WebSocketListener createWebSocketListener() {
        return new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                Log.d(TAG, "WebSocket连接成功");
                state = ConnectionState.CONNECTED;
                
                if (messageListener != null) {
                    messageListener.onConnected();
                }
            }
            
            @Override
            public void onMessage(WebSocket webSocket, String text) {
                if (messageListener != null) {
                    messageListener.onMessage(text);
                }
            }
            
            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                if (messageListener != null) {
                    messageListener.onMessage(bytes);
                }
            }
            
            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                Log.d(TAG, "WebSocket正在关闭: " + code + ", " + reason);
                webSocket.close(1000, null);
            }
            
            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                Log.d(TAG, "WebSocket已关闭: " + code + ", " + reason);
                state = ConnectionState.DISCONNECTED;
                
                if (messageListener != null) {
                    messageListener.onDisconnected();
                }
            }
            
            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                state = ConnectionState.FAILED;
                String errorMsg = t.getMessage();
                Log.e(TAG, "WebSocket连接失败: " + errorMsg, t);
                
                if (messageListener != null) {
                    messageListener.onError(errorMsg);
                }
                
                // 记录错误日志
                LogUtils.logError("WebSocket", "连接失败");
            }
        };
    }
} 